import { ROLES, ROLE_PERMISSIONS } from "../config/permissions";

class RBACManager {
  static setUserPermissions(userData) {
    const {
      email,
      role = ROLES.GUEST,
      position,
      customPermissions = [],
    } = userData;

    // 获取角色默认权限
    const rolePermissions = ROLE_PERMISSIONS[role] || [];

    // 根据职位添加额外权限
    const positionPermissions = this.getPositionPermissions(position);

    // 合并所有权限
    const allPermissions = [
      ...new Set([...rolePermissions, ...(customPermissions || [])]),
    ];

    const authData = {
      email,
      role,
      position,
      permissions: allPermissions,
      lastUpdated: new Date().toISOString(),
    };

    // 同时存储到 localStorage
    localStorage.setItem("authData", JSON.stringify(authData));
    localStorage.setItem("userRole", role);
    localStorage.setItem("userPermissions", JSON.stringify(allPermissions));
    return authData;
  }

  static getPositionPermissions(position) {
    // 根据职位分配额外权限
    switch (position) {
      case "公司高管":
        return ["manage_system", "view_analytics"];
      case "部门经理":
        return ["manage_team", "view_analytics"];
      default:
        return [];
    }
  }

  static getUserPermissions() {
    try {
      const authData = localStorage.getItem("authData");
      return authData ? JSON.parse(authData) : null;
    } catch (error) {
      console.error("Error parsing auth data:", error);
      return null;
    }
  }

  static hasPermission(permission) {
    try {
      const authData = this.getUserPermissions();
      return authData?.permissions?.includes(permission) || false;
    } catch (error) {
      console.error("Error checking permission:", error);
      return false;
    }
  }

  static hasRole(role) {
    try {
      const authData = this.getUserPermissions();
      return authData?.role === role;
    } catch (error) {
      console.error("Error checking role:", error);
      return false;
    }
  }

  static clearPermissions() {
    localStorage.removeItem("authData");
  }

  static isAuthenticated() {
    return !!this.getUserPermissions();
  }

  static clearPermissions() {
    localStorage.removeItem("authData");
    localStorage.removeItem("userRole");
    localStorage.removeItem("userPermissions");
  }
}

export default RBACManager;
